<template>
  <view class="template-classify">

    <view class="tn-classify__wrap" :style="{paddingTop: vuex_custom_bar_height -40 + 'px'}">
      
      <!-- 搜索框 -->
      <view class="tn-classify__search--wrap tn-flex tn-flex-col-center tn-flex-row-center tn-border-solids-bottom">
        <view class="tn-classify__search__box tn-flex tn-flex-col-center tn-flex-row-center tn-bg-gray--light tn-color-gray--dark">
          <view class="tn-classify__search__icon tn-icon-search"></view>
          <view class="tn-classify__search__text">请输入检索内容</view>
        </view>
      </view>
      
      <!-- 分类列表和内容 -->
      <view class="tn-classify__container tn-bg-gray--light">
        <view class="tn-classify__container__wrap tn-flex tn-flex-nowrap tn-flex-row-around tn-bg-white">
          <!-- 左边容器 -->
          <scroll-view class="tn-classify__left-box tn-flex-basic-sm" :scroll-top="leftScrollViewTop" scroll-y scroll-with-animation :style="{height: scrollViewHeight + 'px'}">
            <view
              v-for="(item, index) in tabbar"
              :key="index"
              :id="`tabbar_item_${index}`"
              class="tn-classify__tabbar__item tn-flex tn-flex-col-center tn-flex-row-center"
              :class="[tabbarItemClass(index)]"
              @tap.stop="clickClassifyNav(index)">
              <view class="tn-classify__tabbar__item__title">{{ item }}</view>
            </view>
          </scroll-view>
          
          <!-- 右边容器 -->
          <scroll-view class="tn-classify__right-box" scroll-y :scroll-top="rightScrollViewTop" :style="{height: scrollViewHeight + 'px'}">
            <block v-if="classifyContent.subClassify && classifyContent.subClassify.length > 0">
              <view class="tn-classify__content">
                <!-- 推荐商品轮播图 -->
                <view class="tn-classify__content__recomm">
                  <tn-swiper v-if="classifyContent.recommendProduct.length > 0" class="tn-classify__content__recomm__swiper" :list="classifyContent.recommendProduct" :height="200" :effect3d="true"></tn-swiper>
                </view>
                
                <!-- 分类内容子栏目 -->
                <view v-if="currentTabbarIndex==index" v-for="(item,index) in classifyContent.subClassify" :key="index" class="tn-classify__content__sub-classify">
                  <view class="tn-classify__content__sub-classify--title tn-text-lg tn-padding-top-sm">{{ item.title }}</view>
                  <!-- 如果是成员 -->
                  <view v-if="index==0" class="tn-classify__content__sub-classify__content tn-flex tn-flex-wrap tn-flex-col-center tn-flex-row-left">
                    <view
                      v-for="(sub_item,sub_index) in item.classify"
                      :key="sub_index"
                      class="tn-classify__content__sub-classify__content__item tn-flex tn-flex-wrap tn-flex-row-center"
                    >
                      <view class="tn-classify__content__sub-classify__content__image tn-flex tn-flex-col-center tn-flex-row-center" @click.stop="toUser(sub_item._id, sub_item.classifyId)">
                        <image :src="sub_item.image" mode="aspectFill"></image>
                      </view>
                      <view class="tn-text-ellipsis-2 tn-margin-bottom-sm">{{ sub_item.title }}</view>
                    </view>
                  </view>
				  <!-- 如果是其它 -->
				  <view v-if="index!=0" v-for="(sub_item, sub_index) in item.classify" :key="sub_index">
					<view class="article-shadow" @click.stop="toArticle(sub_item._id, sub_item.classifyId)">
					  <view class="tn-flex">
						<view class="image-pic tn-margin-sm" :style="'background-image:url(' + sub_item.image + ')'">
						  <view class="image-article">
						  </view>
						</view>
						<view class="tn-margin-sm tn-padding-top-xs" style="width: 100%;">
						  <view class="tn-text-bold clamp-text-1">
							{{ sub_item.title }}
						  </view>
						  <view class="tn-padding-top-xs" style="min-height: 100rpx;">
							<text class=" tn-text-sm tn-color-gray clamp-text-2">
							  {{ sub_item.desc }}
							</text>
						  </view>
						</view>
					  </view>
					</view>
				  </view>
                </view>

              </view>
              
              <view class="tn-padding-bottom"></view>
            </block>
          </scroll-view>
        </view>
      </view>
    </view>
	<!-- 引用组件 -->
	<tn-skeleton :show="showSkeleton"></tn-skeleton>
	<tn-tabbar :value="1" :list="tabbarList" activeColor="#838383" inactiveColor="#AAAAAA"
		activeIconColor="tn-cool-bg-color-7" :animation="true" :safeAreaInsetBottom="true" @toIndex="toIndex">
	</tn-tabbar>

  </view>
</template>

<script>
	const db = uniCloud.database()
	const bannerCollection = db.collection('opendb-banner')
	const memberCollection = db.collection('lab-member')
	const artitleCollection = db.collection('lab-artitle')
	const contentCollection = db.collection('opendb-news-articles')
  export default {
    name: 'templateShopClassify',
    data() {
      return {
		  // 底部tabbar菜单数据
			tabbarList: [
			  {
				title: '首页',
				activeIcon: 'home',
				inactiveIcon: 'home-fill'
			  },
			  {
				title: '发布',
				activeIcon: 'discover-planet',
				inactiveIcon: 'discover-planet-fill',
				activeIconColor: '#FFFFFF',
				inactiveIconColor: '#FFFFFF',
				iconSize: 50,
				out: true
			  },
			  {
				title: '我的',
				activeIcon: 'my',
				inactiveIcon: 'my-fill',
				dot: false
			  }
			],
        // 侧边栏分类数据
        tabbar: ['成员','论文','会议','竞赛','专利','软著','文章'],
        // 分类里面的内容信息
        classifyContent: {
          // 推荐商品
          recommendProduct: [],
          // 子栏目
          subClassifyTabbar: [],
          // 显示子栏目分类选项
          showSubClassifyTabbar: true,
          // 每个子栏目下的内容
          subClassify: [
            {
              title: '成员',
              classify: []
            },
            {
              title: '论文',
              classify: []
            },
            {
              title: '会议',
              classify: []
            },
            {
              title: '竞赛',
              classify: []
            },
            {
              title: '专利',
              classify: []
            },
			{
			  title: '软著',
			  classify: []
			},
			{
			  title: '文章',
			  classify: []
			}
          ]
        },
        // 分类菜单item的信息
        tabbarItemInfo: [],
        // scrollView的top值
        scrollViewBasicTop: 0,
        // scrollView的高度
        scrollViewHeight: 0,
        // 左边scrollView的滚动高度
        leftScrollViewTop: 0,
        // 右边scrollView的滚动高度
        rightScrollViewTop: 0,
        // 当前选中的tabbar序号
        currentTabbarIndex: 0,
		showSkeleton: true,
      }
    },
    computed: {
      tabbarItemClass() {
        return index => {
          if (index === this.currentTabbarIndex) {
            return 'tn-classify__tabbar__item--active tn-bg-white'
          } else {
            let clazz = 'tn-bg-gray--light'
            if (this.currentTabbarIndex > 0 && index === this.currentTabbarIndex - 1) {
              clazz += ' tn-classify__tabbar__item--active--prev'
            }
            if (this.currentTabbarIndex < this.tabbar.length && index === this.currentTabbarIndex + 1) {
              clazz += ' tn-classify__tabbar__item--active--next'
            }
            return clazz
          }
        }
      }
    },
	onLoad() {
		// 获取轮播图
		this.getBanner()
		// 获取成员信息
		this.getMember()
		// 获取成果信息
		this.getArtitle()
		// 获取文章信息
		this.getContent()
	},
    onReady() {
      this.$nextTick(() => {
        this.getScrollViewInfo()
        this.getTabbarItemRect()
      })
    },
    methods: {
		async toIndex(index) {
			if (index == 0) {
				uni.switchTab({
					url: '/pages/list/list'
				})
			} else if (index == 2) {
				uni.switchTab({
					url: '/pages/ucenter/ucenter'
				})
			}
		},
      // 获取scrollView的高度信息
      getScrollViewInfo() {
        // 获取搜索栏的bottom信息，然后用整个屏幕的可用高度减去bottom的值即可获取scrollView的高度(防止双重滚动)
        this._tGetRect('.tn-classify__search--wrap').then((rect) => {
          // 如果获取失败重新获取
          if (!rect) {
            setTimeout(() => {
              this.getScrollViewInfo()
            }, 10)
            return
          }
          // 获取当前屏幕的可用高度
          const systemInfo = uni.getSystemInfoSync()
          this.scrollViewBasicTop = systemInfo.statusBarHeight + rect.bottom + uni.upx2px(10)
          this.scrollViewHeight = systemInfo.safeArea.height + systemInfo.statusBarHeight - rect.bottom - uni.upx2px(10)
        })
      },
      // 获取分类菜单每个item的信息
      getTabbarItemRect() {
        let view = uni.createSelectorQuery().in(this)
        for (let i = 0; i < this.tabbar.length; i++) {
          view.select('#tabbar_item_' + i).boundingClientRect()
        }
        view.exec(res => {
          if (!res.length) {
            setTimeout(() => {
              this.getTabbarItemRect()
            }, 10)
            return
          }
          
          // 将每个分类item的相关信息
          res.map((item) => {
            this.tabbarItemInfo.push({
              top: item.top,
              height: item.height
            })
          })
        })
      },
	  // 获取默认轮播图
	  async getBanner() {
	  	let bannerList = await bannerCollection
	  		.get().then((res) => {
	  			// 设置默认轮播图
	  			let imageList = res.result.data
	  			imageList.forEach(item => {
	  				if (item.status == true) {
	  					this.classifyContent.recommendProduct.unshift({
	  						title: item.title,
	  						image: item.bannerfile.url,
	  					})
	  				}
	  			})
	  		}).catch((err) => {
	  			uni.hideLoading()
	  			uni.showModal({
	  				content: err,
	  				showCancel: false
	  			})
	  		})
	  },
	  // 获取成员
	  async getMember(){
		  await memberCollection.get()
		  .then((res) =>{
			  let infoList = res.result.data
			  infoList.forEach((item, index) => {
				  if(item.status == true){
					  this.classifyContent.subClassify[0].classify.unshift({
						  title: item.name,
						  image: item.avatorfile.url,
						  _id:   item._id,
						  classifyId: '成员',
					  })
				  }
			  })
		  }).catch((err) =>{
			  uni.hideLoading()
			  uni.showModal({
			  	content: err,
			  	showCancel: false
			  })
		  })
	  },
	  // 获取成果
	  async getArtitle(){
		await artitleCollection.get()
		  .then((res) =>{
			  let infoList = res.result.data
			  infoList.forEach((item, index) =>{
				  if(item.status == true){
					  this.classifyContent.subClassify[item.classifyId + 1].classify.unshift({
						title: item.label,
						image: item.imageList[0].url,
						desc: item.desc,
						_id:   item._id,
						classifyId: '成果',
					})
				  }
			  })
			  this.showSkeleton = false
		  }).catch((err) =>{
			  uni.hideLoading()
			  uni.showModal({
			  	content: err,
			  	showCancel: false
			  })
		  })
	  },
	  // 获取文章
	  async getContent(){
	  		await contentCollection.get()
	  		  .then((res) =>{
	  			  let infoList = res.result.data
	  			  infoList.forEach((item, index) =>{
					  this.classifyContent.subClassify[6].classify.unshift({
						title: item.title,
						image: item.avatar,
						desc: item.excerpt,
						_id:   item._id,
						classifyId: '文章',
	  				  })
	  			  })
	  			  this.showSkeleton = false
	  		  }).catch((err) =>{
	  			  uni.hideLoading()
	  			  uni.showModal({
	  			  	content: err,
	  			  	showCancel: false
	  			  })
	  		  })
	  },
	  // 查看成员简历
	  toUser(uid, classifyId) {
		  if(classifyId == '成员'){
			  uni.navigateTo({
			  	url: '/pages/list/member/member?uid=' + uid,
			  	animationType: 'fade-in'
			  })
		  }
	  },
	  // 查看文章详情
	  toArticle(uid, classifyId) {
	  		  if(classifyId == '文章'){
	  			  uni.navigateTo({
	  			  	url: '/pages/list/detail?uid=' + uid,
	  			  	animationType: 'fade-in'
	  			  })
	  		  }else if(classifyId == '成果'){
			  uni.navigateTo({
				url: '/pages/list/achieve?uid=' + uid,
				animationType: 'fade-in'
			  })
		  }
	  },
      // 点击了分类导航
      clickClassifyNav(index) {
        if (this.currentTabbarIndex === index) {
          return
        }
        this.currentTabbarIndex = index
        
        this.handleLeftScrollView(index)
        this.switchClassifyContent()
      },
      // 点击分类后，处理scrollView滚动到居中位置
      handleLeftScrollView(index) {
        const tabbarItemTop = this.tabbarItemInfo[index].top - this.scrollViewBasicTop
        if (tabbarItemTop > this.scrollViewHeight / 2) {
          this.leftScrollViewTop = tabbarItemTop - (this.scrollViewHeight / 2) + this.tabbarItemInfo[index].height
        } else {
          this.leftScrollViewTop = 0
        }
      },
      // 切换对应分类的数据
      switchClassifyContent() {
        this.rightScrollViewTop = 1
        this.$nextTick(() => {
          this.rightScrollViewTop = 0
        })
        this.classifyContent.subClassify[0].title = this.tabbar[this.currentTabbarIndex]
      }
    }
  }
</script>

<style lang="scss" scoped>
  .tn-classify {
    
    /* 搜索栏 start */
    &__search {
      &--wrap {
        height: 126rpx;
      }
      
      &__box {
        flex: 1;
        text-align: center;
        padding: 20rpx 0;
        margin: 0 30rpx;
        border-radius: 60rpx;
        font-size: 26rpx;
      }
      
      &__icon {
        padding-right: 10rpx;
      }
    }
    /* 搜索栏 end */
    
    /* 分类列表和内容 strat */
    &__container {
      padding-top: 10rpx;
    }
    
    &__left-box {
      
    }
    
    &__right-box {
      background-color: #FFFFFF;
    }
    /* 分类列表和内容 end */
    
    /* 侧边导航 start */
    &__tabbar {
      &__item {
        height: 90rpx;
        
        &:first-child {
          border-top-right-radius: 0rpx;
        }
        
        &:last-child {
          border-bottom-right-radius: 0rpx;
        }
        
        &--active {
          background-color: #FFFFFF;
          position: relative;
          font-weight: bold;
          
          &::before {
            content: '';
            position: absolute;
            width: 12rpx;
            height: 40rpx;
            top: 50%;
            left: 0;
            background-color: $tn-main-color;
            border-radius: 12rpx;
            transform: translateY(-50%) translateX(-50%);
          }
          
          &--prev {
            border-bottom-right-radius: 26rpx;
          }
          
          &--next {
            border-top-right-radius: 26rpx;
          }
        }
      }
    }
    /* 侧边导航 end */
    
    /* 分类内容 start */
    &__content {
      margin: 18rpx;
      
      /* 推荐商品 start */
      &__recomm {
        margin-bottom: 40rpx;
        
        &__swiper {
          
        }
      }
      /* 推荐商品 end */
      
      /* 子栏目 start */
      &__sub-classify {
        margin-bottom: 20rpx;
        
        &--title {
          font-weight: bold;
          margin-bottom: 18rpx;
        }
        
        &__content {
          
          &__item {
            width: 33%;
          }
          
          &__image {
            background-color: rgba(188, 188, 188, 0.1);
            border-radius: 12rpx;
            margin: 10rpx;
            margin-left: 0;
            width: 100%;
            height: 160rpx;
            overflow: hidden;
            border: 1rpx solid rgba(0,0,0,0.02);
            
            image {
              width: 100%;
              height: 160rpx;
            }
          }
          
          &__title {
            margin-right: 20rpx;
			overflow: hidden;
          }
        }
      }
      /* 子栏目 end */
    }
    /* 分类内容 end */
  }
  
  /* 资讯主图 start*/
  .image-article {
    border-radius: 8rpx;
    border: 1rpx solid #F8F7F8;
    width: 200rpx;
    height: 200rpx;
    position: relative;
  }
  
  .image-pic {
    background-size: cover;
    background-repeat: no-repeat;
    // background-attachment:fixed;
    background-position: top;
    border-radius: 8rpx;
  }
  
  .article-shadow {
    border-radius: 15rpx;
    box-shadow: 0rpx 0rpx 50rpx 0rpx rgba(0, 0, 0, 0.07);
  }
  
  /* 文字截取*/
  .clamp-text-1 {
    -webkit-line-clamp: 1;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  
  .clamp-text-2 {
    -webkit-line-clamp: 4;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  
  /* 标签内容 start*/
  .tn-tag-content {
    &__item {
      display: inline-block;
      line-height: 35rpx;
      padding: 5rpx 25rpx;
  
      &--prefix {
        padding-right: 10rpx;
      }
    }
  }
  
  /* 标签内容 end*/
</style>
